<template>
  <div class="eq_container eq_dashboard_container">
    <div class="app-container detail-head">
      <div class="top-block-frm">
        <div class="tt">
          {{ id ? '编辑集合' : '新增集合' }}
          <div>
            <el-button size="mini" type="success" icon="el-icon-check" @click="toSave" v-if="form.status!=2">保存</el-button>
            <el-button v-if="id && form.status !=2" size="mini" type="danger" icon="el-icon-delete" @click="toDelete">删除</el-button>
          </div>
        </div>
      </div>

      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px" size="small" v-loading="loading">
        <!-- 基本信息 -->
        <el-card shadow="never" class="mb-2">
          <div slot="header" class="left-title">基本信息</div>
          <el-row :gutter="20">
            <el-col :md="12">
              <el-form-item label="主标题" prop="title">
                <el-input v-model="form.title" placeholder="请输入主标题" clearable />
              </el-form-item>
              <el-form-item label="副标题" prop="subtitle">
                <el-input v-model="form.subtitle" placeholder="请输入副标题" clearable />
              </el-form-item>
              <el-form-item label="关联产品" prop="products">
              <el-select
                v-model="form.products"
                multiple
                filterable
                placeholder="请选择要加入该集合的产品"
                style="width: 100%;"
              >
                <el-option
                  v-for="p in productOptions"
                  :key="p.value"
                  :label="p.label"
                  :value="p.value"
                />
              </el-select>
            </el-form-item>
            </el-col>

            <el-col :md="12">
              <el-form-item v-if="id" label="状态">
                <el-tag :type="statusTagType" effect="light" :key="form.status">
                  {{ statusText }}
                </el-tag>
                <el-button
                  v-if="form.status === 0"
                  size="small"
                  class="ttrtbtn"
                  type="success"
                  style="margin-left: 10px;"
                  icon="el-icon-upload2"
                 @click="publish"
                >上架发布
                </el-button>
                <el-button
                  v-if="form.status === 1"
                  size="small"
                  class="ttrtbtn"
                  type="default"
                  style="margin-left: 10px;"
                 icon="el-icon-download"
                 @click="unPublish"
                >下架隐藏
                </el-button>
              </el-form-item>
             <!-- 新增时自己选状态 -->
              <el-form-item v-else label="状态" prop="status">
                <el-select v-model="form.status" placeholder="请选择状态" style="width: 100%;">
                  <el-option
                    v-for="item in productStatusOption"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>

        <!-- <el-card shadow="never" class="mb-2">
          <div slot="header" class="left-title">所有产品</div>
          <el-table
            v-loading="loading"
            :data="list"
            border
            size="mini"
            @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column label="ID" align="left" prop="id" />
          <el-table-column label="产品名" align="left" prop="name"/>
          <el-table-column label="主标题" align="left" prop="title"/>
          <el-table-column label="副标题" align="left" prop="subtitle"/>
          <el-table-column label="主图" align="left" min-width="200">
            <template slot-scope="scope">
              <div class="image-list">
                <img
                  v-for="(url, index) in parseImageList(scope.row.images)"
                  :key="index"
                  :src="url"
                  class="product-image"
                  @click="handlePreview(url)"
                />
              </div>
            </template>
          </el-table-column>
          <el-table-column label="缩略图" align="left" width="120">
            <template slot-scope="scope">
              <img
                v-if="parseThumbnail(scope.row.thumbnail_image)"
               :src="parseThumbnail(scope.row.thumbnail_image)"
               class="thumbnail-image"
               @click="handlePreview(parseThumbnail(scope.row.thumbnail_image))"
              />
              <span v-else>—</span>
            </template>
          </el-table-column>
          <el-table-column label="最低价格" align="left" prop="lowest_price"/>
          <el-table-column label="货币" align="left" prop="currency"/>
          <el-table-column label="状态" align="left" prop="status">
            <template slot-scope="scope">
              <el-tag size="mini" :type="scope.row.status_cls">
                {{ scope.row.status_txt }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" align="left" prop="create_time" width="90"/>
          <el-table-column label="操作" width="150px" fixed="right" align="left">
            <template slot-scope="scope">
              <el-button
                  size="mini"
                  type="text"
                  icon="ti ti-edit"
                  @click="toEdit(scope.row)"
              >编辑详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        </el-card> -->

        <!-- 富文本编辑 -->
        <el-card shadow="never" class="mb-2">
          <div slot="header" class="left-title">内容描述</div>
          <rc-editor
            api-key=""
            v-model="form.description"
          />
        </el-card>

        <!-- 关联产品列表 -->
        <el-card shadow="never" class="mb-2">
          <div slot="header" class="left-title">关联产品</div>
          <el-table
            v-loading="loading"
            :data="productList"
            border
            size="mini"
          >
            <el-table-column label="ID" align="left" prop="id" />
            <el-table-column label="产品名" align="left" prop="name"/>
            <el-table-column label="主标题" align="left" prop="title"/>
            <el-table-column label="副标题" align="left" prop="subtitle"/>
            <!-- <el-table-column label="描述url" align="left" prop="content_url"/> -->
            <el-table-column label="主图" align="left" min-width="200">
              <template slot-scope="scope">
                <div class="image-list">
                  <img
                    v-for="(url, index) in parseImageList(scope.row.images)"
                    :key="index"
                    :src="url"
                    class="product-image"
                    @click="handlePreview(url)"
                  />
                </div>
              </template>
            </el-table-column>
            <!-- ✅ 缩略图（单图） -->
            <el-table-column label="缩略图" align="left" width="120">
              <template slot-scope="scope">
                <img
                  v-if="parseThumbnail(scope.row.thumbnail_image)"
                 :src="parseThumbnail(scope.row.thumbnail_image)"
                 class="thumbnail-image"
                 @click="handlePreview(parseThumbnail(scope.row.thumbnail_image))"
                />
                <span v-else>—</span>
              </template>
            </el-table-column>
            <el-table-column label="最低价格" align="left" prop="lowest_price"/>
            <el-table-column label="货币" align="left" prop="currency"/>
            <el-table-column label="状态" align="left" prop="status">
              <template slot-scope="scope">
                <el-tag size="mini" :type="scope.row.status_cls">
                  {{ scope.row.status_txt }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="创建时间" align="left" prop="create_time" width="90"/>
            <el-table-column label="操作" width="150px" fixed="right" align="left">
              <template slot-scope="scope">
                <el-button
                    size="mini"
                    type="text"
                    icon="ti ti-edit"
                    @click="toEdit(scope.row)"
                >编辑产品
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-form>
    </div>

    <!-- 图片预览弹框 -->
      <el-dialog
        title="图片预览"
        :visible.sync="previewVisible"
        width="40%"
        :show-close="true"
        :close-on-click-modal="true"
      >
        <div style="text-align:center;">
          <img
            :src="previewImage"
            alt="预览图"
            style="max-width:100%; max-height:80vh; border-radius:8px; box-shadow:0 2px 8px rgba(0,0,0,0.2);"
          />
        </div>
      </el-dialog>
  </div>
</template>

<script>
import { getCollectionById, editCollectionById ,getProductList} from '@/api/product'
import { parseImageList, parseThumbnail } from '@/utils/common'
import VarientEdit from '@/layout/components/varientConfig/edit.vue'
import RcEditor from '@/layout/components/Editor/index.vue'

export default {
  name: 'ProductEdit',
  components: { 
    // Editor,
    VarientEdit,
    RcEditor
   },
  data() {
    return {
      id: '',
      loading: false,
      statusText: '',     
      statusTagType: '', 
      productStatusOption: this.hashmap.productStatusOption,
      productOptions:[],
      previewVisible: false,
      previewImage: '',
      productList:[], //关联的产品列表
      list:[],
      multipleSelection: [], // 存放选中的产品

      form: {
        collection_id: null,
        title: '',
        subtitle: '',
        description: '',
        products: [],
        status: 1
      },
      
      rules: {
        title: [{ required: true, message: '请输入主标题', trigger: 'blur' }],
      },
    }
  },

  watch: {
    '$route.query.id'(newId) {
      this.id = newId || null
      if (this.id) {
        this.getCollectionById()
      }
    }
  },

  computed: {
  },


  created() {
    this.id = this.$route.query.id || null
    if (this.id) this.getCollectionById()

    this.getProductList()
  },



  methods: {
    parseImageList,
    parseThumbnail,

    getCollectionById() {
      this.loading = true
      getCollectionById({ 
        collection_id: this.id 
        }).then(res => {
        if (res && res.code === 0 && res.data) {
          const data = res.data
          this.form = data
          this.productList = (data.products || []).map(p => {
            const statusObj = this.findJsonByKeyValue(this.productStatusOption, 'value', p.status)
            return {
              ...p,
              status_txt: statusObj ? statusObj.label : '未知',
              status_cls: statusObj ? statusObj.typeClass : ''
            }
          })

          this.statusText = this.findJsonByKeyValue(this.productStatusOption, 'value', data.status).label || ''
          this.statusTagType = this.findJsonByKeyValue(this.productStatusOption, 'value', data.status).typeClass || ''

          this.form.products = (data.products || [])
            .filter(p => p && p.id != null)
            .map(p => p.id)
        }
      }).finally(()=>{
        this.loading = false
      })
    },

    toSave() {
      const $this = this
      $this.$refs.formRef.validate(valid => {
        if (!valid) return
        $this.$confirm('确认提交？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'info'
        }).then(() => {
          $this.loading = true
          const isEdit = !!$this.id
          const params = { ...$this.form }

          // 编辑时带上 collection_id
          if (isEdit) {
            params.collection_id = Number($this.id)
          }else{
            delete params.collection_id
          }
          console.log('保存集合传参：', params)

          editCollectionById(params)
            .then((res) => {
              if (res && res.code === 0) {
                const newId = isEdit ? $this.id : (res.data && res.data.id)
                $this.$message.success(isEdit ? '修改成功' : '新增成功')
                // this.$router.push({
                //   path: `/collection/collectionList`
                // })
                if (!isEdit && newId) {
                  $this.$router.replace({
                    path: '/collection/collectionDetail',
                    query: { id: newId }
                  })
                  $this.id = newId
                  $this.getCollectionById()
                }

                if (isEdit) {
                  $this.getCollectionById()
                }
              } else {
                $this.$message.error(res?.msg || (isEdit ? '修改失败' : '新增失败'))
              }
            })
            .finally(() => {
              $this.loading = false
            })
        }).catch(() => {})
      })
    },

    getProductList(){
      getProductList({
        'page':1,
        'page_size':5000,
        'status':1
      }).then((res)=>{
        if(res){
          this.productOptions = res.data.list.map((item) => {
            return {
              value: item.id,
              label: item.name,
              key: item.name,
              type: item.id
            }
          })
        }
      })
    },

    // getProductList(){
    //   getProductList({
    //     'page':this.page,
    //     'page_size':this.page_size,
    //     'status':1
    //   }).then((res)=>{
    //     if(res){
    //       this.total = res.data.total || 0
    //       this.list = res.data.list.map(item => ({
    //         ...item,
    //         status_txt: this.findJsonByKeyValue(this.productStatusOption, 'value', item.status).label || '',
    //         status_cls: this.findJsonByKeyValue(this.productStatusOption, 'value', item.status).typeClass || '',
    //       }))
    //     }

    //   })
    // },

    handlePreview(url) {
      this.previewImage = url
      this.previewVisible = true
    },

    // 通用状态更新方法
    updateStatus (newStatus, confirmText, successMsg, afterSuccess) {
      if (!this.id) return

      this.$confirm(confirmText, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true
        editCollectionById({
          collection_id: Number(this.id),
          status: newStatus
        })
          .then(res => {
            if (res && res.code === 0) {
              if (newStatus == 1 ) {
                this.form.status = newStatus
              }
              this.$message.success(successMsg)

              if (typeof afterSuccess === 'function') {
                afterSuccess()
              }
            } else {
              this.$message.error(res?.msg || '操作失败')
            }
          })
          .finally(() => {
            this.loading = false
            this.getCollectionById()
          })
      }).catch(() => {})
    },

    // 删除：status = 2
    toDelete () {
      this.updateStatus(2,'确认是否删除该集合？','删除成功',() => {
        this.$router.push({ path: '/collection/collectionList' })
      })
    },

     // 上架：status = 1
    publish () {
      this.updateStatus(1,'确认将该集合上架发布吗？','上架成功')
    },

    // 下架：status = 0
    unPublish () {
      this.updateStatus(0,'确认将该集合下架隐藏吗？','下架成功',() => {
      })
    },

    toEdit (row) {
      this.$router.push({
        path: `/product/detail?id=${row.id}`
      })
    },

    // 多选
    // handleSelectionChange(val) {
    //   this.multipleSelection = val
    //   this.form.products = val.map(item => item.id)
    // },


  }
}
</script>
<style src="@/styles/normalstyle.css"></style>
<style scoped>
.preview-img {
  width: 100px;
  height: 100px;
  object-fit: cover;
  margin-bottom: 8px;
  border-radius: 8px;
  border: 1px solid #eee;
}
.mb-2 { margin-bottom: 16px; }
.mt-2 { margin-top: 12px; }

.left-title{
  padding-left: 5px;
  border-left: 3px solid #4974e1;
}

</style>
